package com.yougou.ui.mine;

import android.content.Intent;
import android.net.Uri;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.cardview.widget.CardView;

import com.bumptech.glide.Glide;
import com.yougou.R;
import com.yougou.base.BaseFragment;
import com.yougou.data.model.User;
import com.yougou.ui.address.AddressListActivity;
import com.yougou.ui.login.LoginActivity;
import com.yougou.utils.ToastUtils;
import com.yougou.utils.UserManager;

public class MineFragment extends BaseFragment {
    
    private CardView mCardUserInfo;
    private ImageView mIvAvatar;
    private TextView mTvUsername;
    private TextView mTvUserDesc;
    
    private LinearLayout mLlOrderPayment;
    private LinearLayout mLlOrderShipping;
    private LinearLayout mLlOrderReceive;
    private LinearLayout mLlOrderComplete;
    
    private TextView mTvMyFavorite;
    private TextView mTvSettings;
    private TextView mTvLogout;
    
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_mine;
    }
    
    @Override
    public void onResume() {
        super.onResume();
        // 每次显示时刷新用户信息
        updateUserInfo();
    }
    
    @Override
    protected void initView(View view) {
        mCardUserInfo = view.findViewById(R.id.card_user_info);
        mIvAvatar = view.findViewById(R.id.iv_avatar);
        mTvUsername = view.findViewById(R.id.tv_username);
        mTvUserDesc = view.findViewById(R.id.tv_user_desc);
        
        mLlOrderPayment = view.findViewById(R.id.ll_order_payment);
        mLlOrderShipping = view.findViewById(R.id.ll_order_shipping);
        mLlOrderReceive = view.findViewById(R.id.ll_order_receive);
        mLlOrderComplete = view.findViewById(R.id.ll_order_complete);
        
        mTvMyFavorite = view.findViewById(R.id.tv_my_favorite);
        mTvSettings = view.findViewById(R.id.tv_settings);
        mTvLogout = view.findViewById(R.id.tv_logout);
        
        // 用户信息卡片点击
        mCardUserInfo.setOnClickListener(v -> {
            if (!UserManager.isLogin()) {
                // 未登录，跳转到登录页面
                Intent intent = new Intent(requireContext(), LoginActivity.class);
                startActivity(intent);
            } else {
                // 已登录，跳转到个人信息页面
                Intent intent = new Intent(requireContext(), UserInfoActivity.class);
                startActivity(intent);
            }
        });
        
        // 订单状态点击事件
        mLlOrderPayment.setOnClickListener(v -> openOrderList(1));
        mLlOrderShipping.setOnClickListener(v -> openOrderList(2));
        mLlOrderReceive.setOnClickListener(v -> openOrderList(3));
        mLlOrderComplete.setOnClickListener(v -> openOrderList(4));
        
        // 我的收藏
        mTvMyFavorite.setOnClickListener(v -> {
            if (checkLogin()) {
                Intent intent = new Intent(requireContext(), FavoriteActivity.class);
                startActivity(intent);
            }
        });
        
        // 设置（修改为地址管理）
        mTvSettings.setText("地址管理");
        mTvSettings.setOnClickListener(v -> {
            if (checkLogin()) {
                Intent intent = new Intent(requireContext(), AddressListActivity.class);
                startActivity(intent);
            }
        });
        
        // 退出登录
        mTvLogout.setOnClickListener(v -> {
            UserManager.logout();
            updateUserInfo();
            ToastUtils.show(requireContext(), "已退出登录");
        });
    }
    
    @Override
    protected void initData() {
        updateUserInfo();
    }


    private void updateUserInfo() {
        if (UserManager.isLogin()) {
            User user = UserManager.getCurrentUser();
            if (user != null) {
                mTvUsername.setText(user.getUsername());
                mTvUserDesc.setText("欢迎回来");
                mTvLogout.setVisibility(View.VISIBLE);

                // 加载用户头像
                String avatar = user.getAvatar();
                android.util.Log.d("MineFragment", "加载头像: " + avatar);
                if (avatar != null && !avatar.isEmpty()) {
                    if (avatar.startsWith("content://")) {
                        Glide.with(this)
                                .load(Uri.parse(avatar))
                                .skipMemoryCache(true)
                                .diskCacheStrategy(com.bumptech.glide.load.engine.DiskCacheStrategy.NONE)
                                .placeholder(R.drawable.ic_mine)
                                .error(R.drawable.ic_mine)
                                .circleCrop()
                                .into(mIvAvatar);
                    } else {
                        java.io.File avatarFile = new java.io.File(avatar);
                        android.util.Log.d("MineFragment", "文件存在: " + avatarFile.exists() + ", 大小: " + avatarFile.length());

                        Glide.with(this)
                                .load(avatarFile)
                                .skipMemoryCache(true)
                                .diskCacheStrategy(com.bumptech.glide.load.engine.DiskCacheStrategy.NONE)
                                .placeholder(R.drawable.ic_mine)
                                .error(R.drawable.ic_mine)
                                .circleCrop()
                                .into(mIvAvatar);
                    }
                } else {
                    android.util.Log.d("MineFragment", "头像路径为空");
                    mIvAvatar.setImageResource(R.drawable.ic_mine);
                }
            }
        } else {
            mTvUsername.setText("游客用户");
            mTvUserDesc.setText("点击登录");
            mTvLogout.setVisibility(View.GONE);
            mIvAvatar.setImageResource(R.drawable.ic_mine);
        }
    }
    
    private boolean checkLogin() {
        if (!UserManager.isLogin()) {
            ToastUtils.show(requireContext(), "请先登录");
            Intent intent = new Intent(requireContext(), LoginActivity.class);
            startActivity(intent);
            return false;
        }
        return true;
    }
    
    
    private void openOrderList(int type) {
        if (checkLogin()) {
            Intent intent = new Intent(requireContext(), com.yougou.ui.order.OrderListActivity.class);
            intent.putExtra(com.yougou.ui.order.OrderListActivity.EXTRA_ORDER_TYPE, type);
            startActivity(intent);
        }
    }
    
}
